import $ from 'jquery';

export default {
    state: {
        id:"",
        username:"",
        token:"",
        is_login:false,
        loading_information:true,
    },
    getters: {
    },

    mutations: {
        updateUser(state,user){
                state.id = user.id;
                state.username = user.username;
                state.is_login = user.is_login;
            },
        updateToken(state,token){
                state.token = token;
            },
        logout(state){
                state.id="";
                state.username="";
                state.token="";
                state.is_login = false;
            },
        updateLoadingInformation(state,loading_information){
                state.loading_information = loading_information;
            }
        },

    actions: {
        login(context,data){
            $.ajax({
                url:"http://localhost:7012/user/account/login/",
                type:"post",
                data:{
                    username: data.username,
                    password: data.password,
                },
                success(resp) {
                    if (resp.message === "success") {
                        localStorage.setItem("JWT_Token",resp.token);
                        context.commit("updateToken", resp.token);
                        data.success(resp);
                    } else {
                        data.error(resp);
                    }
                },
                error(resp) {
                    data.error(resp);
                }
            });
        },
        getInfo(context,data){
              $.ajax({
                url:"http://localhost:7012/user/account/getInfo/",
                type:"post",
                headers:{
                  Authorization:"Bearer "+ context.state.token,
                },
                success(resp){
                if (resp.message === "success"){
                    context.commit("updateUser",{
                        ...resp,
                        is_login: true,
                    });
                    data.success(resp);
                } else {
                    data.error(resp);
                }
              },
                error(resp){
                  data.error(resp);
                }
              });
        },
        logout(context) {
            localStorage.removeItem("JWT_Token");
            context.commit("logout");
        }
    },

    modules: {
    }
}
